package com.mikufufu.blog.utils;

import com.mikufufu.blog.common.entity.Node;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 树形工具类
 * 
 */
public class TreeUtils {

    public static <T, E> Node<T, E> buildTree(Node<T, E> root, Node<T, E> node) {
        if (node.getParentId().equals(root.getId())) {
            root.addChild(node);
        } else {
            for (Node<T, E> child : root.getChildren()) {
                buildTree(child, node);
            }
        }
        return root;
    }

    public static <T, E> List<Node<T,E>> listToTree(List<Node<T, E>> list,E rootId) {
        // 检查输入列表是否为空，若为空则直接返回空列表
        if (StringUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        // 遍历列表
        Map<E, List<Node<T, E>>> nodeMap = list.stream().collect(Collectors.groupingBy(Node<T, E>::getParentId));

        // 返回根节点
        return list.stream().peek(node -> {
            List<Node<T,E>> children = nodeMap.get(node.getId());
            if (StringUtils.isNotEmpty(children)) {
                node.setChildren(children);
            }
        }).filter(node -> node.getParentId().equals(rootId)).collect(Collectors.toList());
    }

}
